package com.example.demo.common;

import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.hwpf.HWPFDocument;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

public class FileReaderUtil {

    public static String readFileContent(MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        String extension = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();

        switch (extension) {
            case "txt":
                return readTxtFile(file.getInputStream());
            case "doc":
                return readDocFile(file.getInputStream());
            case "docx":
                return readDocxFile(file.getInputStream());
            default:
                throw new IllegalArgumentException("不支持的文件格式: " + extension);
        }
    }

     static String readTxtFile(InputStream inputStream) throws IOException {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
            StringBuilder content = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line).append("\n");
            }
            return content.toString();
        }
    }

    public static String readDocFile(InputStream inputStream) throws IOException {
        try (HWPFDocument doc = new HWPFDocument(inputStream);
             WordExtractor extractor = new WordExtractor(doc)) {
            return extractor.getText();
        }
    }

    public static String readDocxFile(InputStream inputStream) throws IOException {
        try (XWPFDocument docx = new XWPFDocument(inputStream);
             XWPFWordExtractor extractor = new XWPFWordExtractor(docx)) {
            return extractor.getText();
        }
    }
}